import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'index.dart';
import '../../../common/utils/index.dart';
import '../../../common/values/images.dart';

/// 我的页面视图
/// 
/// 显示专家个人信息和相关功能入口
/// 包含专家基本信息、功能菜单和退出登录等
/// 遵循GetX视图标准化结构
class MyIndexPage extends GetView<MyIndexController> {
  const MyIndexPage({super.key});

  // 主视图构建方法
  Widget _buildView() {
    // 统一的错误和加载状态处理
    if (controller.hasError.value) {
      return _buildErrorView();
    }
    
    return Column(
      children: [
        // ✅ 固定的用户信息头部区域（不滚动）
        _buildUserHeader(),
        
        // ✅ 可滚动的内容区域（Expanded 让它占据剩余空间）
        Expanded(
          child: RefreshIndicator(
            onRefresh: controller.refreshExpertInfo,
            color: Colors.blue.shade600,
            child: SingleChildScrollView(
              physics: const AlwaysScrollableScrollPhysics(),
              padding: EdgeInsets.zero, // 移除默认padding
              child: Column(
                 children: [
                  SizedBox(height: 16.h),
                  // 专家详细信息卡片
                  _buildExpertDetailsSection(),
                  SizedBox(height: 24.h), // 底部空间
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 构建错误状态视图
  Widget _buildErrorView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.error_outline,
            size: 64.r,
            color: Colors.red.shade400,
          ),
          SizedBox(height: 16.h),
          Text(
            controller.errorMessage.value,
            style: TextStyle(
              fontSize: 16.sp,
              color: Colors.grey.shade600,
            ),
            textAlign: TextAlign.center,
          ),
          SizedBox(height: 24.h),
          ElevatedButton.icon(
            onPressed: controller.resetErrorState,
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue.shade600,
              foregroundColor: Colors.white,
              padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 12.h),
            ),
            icon: Icon(Icons.refresh, size: 20.r),
            label: Text('重试', style: TextStyle(fontSize: 14.sp)),
          ),
        ],
      ),
    );
  }

  /// 构建专家头部信息（固定不滚动 - 欧式优雅风格）
  Widget _buildUserHeader() {
    // 获取状态栏高度
    final statusBarHeight = MediaQuery.of(Get.context!).padding.top;
    // AppBar标准高度是56
    final appBarHeight = 56.h;
    
    return Container(
      width: double.infinity,
      // 动态计算顶部padding，为状态栏和AppBar留出空间
      padding: EdgeInsets.only(
        top: statusBarHeight + appBarHeight + 20.h, // 增大顶部间距
        bottom: 32.h, // 增大底部间距
        left: 24.w,
        right: 24.w,
      ),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Colors.blue.shade600,
            Colors.blue.shade800,
          ],
        ),
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(30.r),
          bottomRight: Radius.circular(30.r),
        ),
        // 阴影效果，让固定头部与滚动内容明显区分
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.15),
            blurRadius: 15.r,
            spreadRadius: 0,
            offset: Offset(0, 5.h),
          ),
        ],
      ),
      child: Row(
        children: [
          // 左侧：专家图标
          _buildExpertIcon(),
          SizedBox(width: 20.w),
          // 右侧：专家信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 专家名称
                _buildExpertName(),
                SizedBox(height: 4.h),
                // 专家机构和职务
                _buildExpertInfo(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建专家图标（使用logo图片）
  Widget _buildExpertIcon() {
    return Container(
      width: 80.w,
      height: 80.w,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(16.r),
        border: Border.all(
          color: Colors.white,
          width: 3.w,
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.15),
            blurRadius: 12.r,
            spreadRadius: 2.r,
            offset: Offset(0, 4.h),
          ),
        ],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(13.r),
        child: Image.asset(
          AssetsImages.logoPng,
          width: 80.w,
          height: 80.w,
          fit: BoxFit.cover,
          errorBuilder: (context, error, stackTrace) {
            // 如果图片加载失败，显示默认图标
            return Container(
              color: Colors.white,
              child: Icon(
                Icons.person_pin,
                size: 40.r,
                color: Colors.blue.shade600,
              ),
            );
          },
        ),
      ),
    );
  }

  /// 构建专家名称
  Widget _buildExpertName() {
    return Text(
      controller.expertDisplayName,
      style: TextStyle(
        fontSize: 24.sp,
        fontWeight: FontWeight.bold,
        color: Colors.white,
      ),
    );
  }

  /// 构建专家信息显示
  Widget _buildExpertInfo() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (controller.expertCorpName.isNotEmpty && 
            controller.expertCorpName != '未设置' && 
            controller.expertCorpName != 'null')
          Text(
            controller.expertCorpName,
            style: TextStyle(
              fontSize: 14.sp,
              color: Colors.white.withOpacity(0.8),
            ),
          ),
        if (controller.expertOfficialCapacity.isNotEmpty && 
            controller.expertOfficialCapacity != '未设置' && 
            controller.expertOfficialCapacity != 'null')
          Text(
            controller.expertOfficialCapacity,
            style: TextStyle(
              fontSize: 12.sp,
              color: Colors.white.withOpacity(0.7),
            ),
          ),
      ],
    );
  }

  /// 构建专家详细信息区域（优雅欧式风格设计）
  Widget _buildExpertDetailsSection() {
    return Container(
      margin: EdgeInsets.fromLTRB(16.w, 0, 16.w, 0),  // 增大左右边距，更优雅
      padding: EdgeInsets.all(20.r),               // 增大内边距
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(20.r),         // 更大的圆角，欧式优雅风格
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.06),      // 加深阴影，增强立体感
            blurRadius: 16.r,
            spreadRadius: 0,
            offset: Offset(0, 4.h),
          ),
          BoxShadow(
            color: Colors.black.withOpacity(0.03),      // 双层阴影，更柔和
            blurRadius: 8.r,
            spreadRadius: 0,
            offset: Offset(0, 2.h),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题（带渐变图标）- 应用设计规范
          Row(
            children: [
              Container(
                padding: EdgeInsets.all(5.r),
                decoration: BoxDecoration(
                  gradient: const LinearGradient(     // 设计规范：主色渐变
                    colors: [Color(0xFFFF6B6B), Color(0xFFD84545)],
                  ),
                  borderRadius: BorderRadius.circular(8.r),
                ),
                child: Icon(
                  Icons.person_outline_rounded,
                  color: Colors.white,
                  size: 14.r,
                ),
              ),
              SizedBox(width: 6.w),
              Text(
                '专家信息',
                style: TextStyle(
                  fontSize: 14.sp,                        // 设计规范：次标题字号
                  fontWeight: FontWeight.bold,
                  color: const Color(0xFF333333),            // 设计规范：文字主色
                ),
              ),
            ],
          ),
          SizedBox(height: 16.h),                 // 增大间距
          
          // 基本信息
          _buildBasicInfoSection(),
          SizedBox(height: 12.h),
          
          // 机构信息
          _buildCorpInfoSection(),
          SizedBox(height: 12.h),
          
          // 联系信息
          _buildContactInfoSection(),
        ],
      ),
    );
  }

  /// 构建基本信息区域（现代化设计）
  Widget _buildBasicInfoSection() {
    return _buildInfoItem(
      label: '姓名',
      value: controller.expertName,
      icon: Icons.badge_outlined,
      iconColor: const Color(0xFF4FC3F7),  // 蓝色
    );
  }

  /// 构建机构信息区域（现代化设计）
  Widget _buildCorpInfoSection() {
    return Column(
      children: [
        _buildInfoItem(
          label: '所属机构',
          value: controller.expertCorpName,
          icon: Icons.apartment_outlined,
          iconColor: const Color(0xFF9C27B0),  // 紫色
        ),
        SizedBox(height: 6.h),
        _buildInfoItem(
          label: '职务',
          value: controller.expertOfficialCapacity,
          icon: Icons.work_outline,
          iconColor: const Color(0xFFFF9800),  // 橙色
        ),
      ],
    );
  }

  /// 构建联系信息区域（现代化设计）
  Widget _buildContactInfoSection() {
    return Column(
      children: [
        _buildInfoItem(
          label: '手机号',
          value: controller.expertPhone,
          icon: Icons.phone_outlined,
          iconColor: const Color(0xFF66BB6A),  // 绿色
        ),
        SizedBox(height: 6.h),
        _buildInfoItem(
          label: '邮箱',
          value: controller.expertEmail,
          icon: Icons.email_outlined,
          iconColor: const Color(0xFF29B6F6),  // 蓝色
        ),
      ],
    );
  }

  /// 构建信息项（优雅欧式设计 - 单行布局）
  Widget _buildInfoItem({
    required String label,
    required String value,
    required IconData icon,
    required Color iconColor,
  }) {
    // 处理null值显示
    final displayValue = (value.isEmpty || value == 'null') ? '未设置' : value;
    
    return Container(
      padding: EdgeInsets.symmetric(vertical: 12.h, horizontal: 16.w),  // 增大内边距
      decoration: BoxDecoration(
        color: const Color(0xFFFAFBFC),  // 更浅的背景色
        borderRadius: BorderRadius.circular(12.r),  // 更大圆角
        border: Border.all(
          color: const Color(0xFFE8EBF0),  // 添加细边框
          width: 1,
        ),
      ),
      child: Row(
        children: [
          // 图标容器（优雅设计）
          Container(
            width: 32.w,
            height: 32.w,
            padding: EdgeInsets.all(7.r),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  iconColor.withOpacity(0.15),
                  iconColor.withOpacity(0.08),
                ],
              ),
              borderRadius: BorderRadius.circular(10.r),
            ),
            child: Icon(
              icon,
              color: iconColor,
              size: 18.r,
            ),
          ),
          SizedBox(width: 12.w),
          // 使用RichText实现单行布局（设计规范）
          Expanded(
            child: RichText(
              text: TextSpan(
                children: [
                  TextSpan(
                    text: '$label：',
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: const Color(0xFF999999),      // 设计规范：文字辅助色
                      fontWeight: FontWeight.w500,
                      fontFamily: 'PingFang SC',     // 确保字体一致
                    ),
                  ),
                  TextSpan(
                    text: displayValue,
                    style: TextStyle(
                      fontSize: 13.sp,
                      color: displayValue == '未设置' 
                          ? const Color(0xFF999999) 
                          : const Color(0xFF333333),  // 设计规范：文字主色
                      fontWeight: FontWeight.w600,
                      fontStyle: displayValue == '未设置' ? FontStyle.italic : FontStyle.normal,
                      fontFamily: 'PingFang SC',
                    ),
                  ),
                ],
              ),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 设置我的页面状态栏样式 - 深色背景使用浅色图标
    SystemUIUtils.setTransparentStatusBarLight();
    
    return GetBuilder<MyIndexController>(
      init: MyIndexController(),
      id: "my_index",
      builder: (_) {
        return Scaffold(
          backgroundColor: const Color(0xFFF8F9FA),  // 设计规范：页面背景色
          extendBodyBehindAppBar: true, // 让body延伸到AppBar下方
          appBar: _buildAppBar(),
          body: _buildView(),
        );
      },
    );
  }
  
  /// 构建应用栏
  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      title: Text(
        '我的',
        style: TextStyle(
          fontSize: 18.sp,
          fontWeight: FontWeight.w600,
        ),
      ),
      backgroundColor: Colors.transparent, // 设置为透明
      foregroundColor: Colors.white,
      elevation: 0, // 移除阴影
      centerTitle: true,
      // ✅ 自动显示返回按钮
      leading: IconButton(
        onPressed: () => Get.back(),
        icon: Icon(
          Icons.arrow_back_ios_new,
          color: Colors.white,
          size: 20.r,
        ),
        tooltip: '返回',
      ),
    );
  }
}
